<template>
  <basic-container>
    <el-dialog :append-to-body="true" :before-close="cancelDialog" :close-on-click-modal="false"
               title="审核初稿" :visible.sync="dialog" custom-class="ledger" fullscreen top="5vh"
               width="1200px">
      <div class="colums">
        <div class="colums_left">
          <div class="colums_left_middle">
            <div class="middleForm ledger">
              <el-form ref="dataForm" :model="form" class="el-dialog__body" label-width="100px">
                <div class="title">项目信息</div>
                <el-form-item label-width="100px" label="项目名称:" prop="projectName">
                  <el-input v-model="form.projectName" placeholder="项目名称" @focus="showProjectDialog()" :rules="{required: true, message: '项目编号不能为空', trigger: ['focus', 'change']}"></el-input>
                </el-form-item>
                <div class="title">审核说明</div>
                <el-row>
                  <el-col>
                    <el-form-item label-width="100px" label="附件：">
                      <el-upload
                        class="upload-demo"
                        ref="upload"
                        action="/admin/sys-file/upload"
                        :headers="{Authorization}"
                        :file-list="fileList"
                        :on-success="handleSuccess"
                        :on-preview="handlePreview"
                        :on-remove="handleRemove"
                        :show-file-list="true">
                        <el-button size="small" type="primary">点击上传</el-button>
                      </el-upload>
                    </el-form-item>
                  </el-col>
                </el-row>
                <div class="title">审核对比分析表初稿</div>
                <el-row>
                  <el-col>
                    <el-button icon="el-icon-plus" size="small" type="primary" @click="onAddItem('')">新建</el-button>
                    <el-button icon="el-icon-document-copy" @click="addSelectedRow">复制</el-button>
                    <el-button icon="el-icon-delete" @click="deleteSelectedRows">删除</el-button>
                    <el-button icon="el-icon-delete-solid" @click="clearTableData">删除全部</el-button>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col>
                    <el-table
                      ref="table"
                      :data="tableData"
                      :model="tableData"
                      v-loading="loading"
                      style="width: 70%;margin: auto"
                      max-height="450"
                      highlight-current-row
                      @selection-change="updateSelectedRows"
                      @current-change="handleCurrentChange"
                    >
                      <el-table-column type="selection" width="55" align="center"></el-table-column>
                      <el-table-column label="序号" width="100">
                        <template #default="{ $index }">
                          <span>{{ $index + 1 }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="名称">
                        <template #default="{ row }">
                          <el-input v-model="row.name" type="textarea" :autosize="{ minRows: 1}"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column label="是否对比表" width="200" align="center">
                        <template #default="{ row }">
                          <template>
                            <el-radio-group v-model="row.compare">
                              <el-radio border style="margin: 0 5px 0 5px" :label="1">是</el-radio>
                              <el-radio border style="margin: 0 5px 0 5px" :label="0">否</el-radio>
                            </el-radio-group>
                          </template>
                        </template>
                      </el-table-column>
                      <el-table-column label="附件" width="280">
                        <template #default="{ row, $index }">
                          <el-upload
                            class="upload-demo"
                            ref="upload"
                            action="/admin/sys-file/upload"
                            :headers="{Authorization}"
                            :on-success="(e) => handleTableSuccess(e, $index)"
                            :on-preview="handlePreview"
                            :on-remove="(file, fileList) => handleTableRemove(file, fileList, $index)"
                            :show-file-list="true"
                            :file-list="row.fileList">
                            <i class="el-icon-paperclip" style="color: #409EFF;"></i>
                          </el-upload>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-col>
                </el-row>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button icon="el-icon-close" size="small" @click="cancelDialog">关闭</el-button>
                <el-button icon="el-icon-check" size="small" type="primary" @click="saveEngineering" :loading="loading">保存</el-button>
                <el-button icon="el-icon-check" size="small" type="primary" @click="submitEngineering" :loading="loading">提交</el-button>
              </span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
    <ChoseProject ref="ChoseProject" :projectDialog="projectDialog" @cancelDialog="closeProjectDialog" @setValue="projectDataHandle"/>
  </basic-container>
</template>


<script>
import ChoseProject from "@/components/audited/ChoseProject.vue";
import {saveEngineering,getReport,submitEngineering} from "@/api/adis/report/reportOpinion";
import {getByProjectId} from "@/api/adis/execute/discover";
import WebDocument from "@/components/form/webDocument.vue";
import {getByPointId} from "@/api/adis/execute/point";

export default {
  components: {WebDocument, ChoseProject},
  // props: {
  //   dialog: Boolean,
  // },
  dictTypes: ['audit_type_1_sub'],
  data(){
    return{
      isHidden:true,
      dialog: false,
      form:{
        employmentDates:[]
      },
      projectDialog:false,
      isView:false,
      tableData:[],
      formDisplay:false,
      pageType:'reportOpinion',
      reportHidden:true,
      auditView: 'ReportAuditType1',
      loading: false,
      Authorization:'',
      fileList:[],
      radio: '1',
      selectedRows: [], // 存储选中的行数据
      selectedRow: {},
    }
  },
  watch: {
    // 检测资料清单，如果被全数删除，立即补充一条空的清单
    tableData(newVal){
      if ((!newVal || newVal.length <= 1) && this.tableData.length <= 0){
        this.onAddItem(this.tableData)
      }
    },
  },
  created() {
    this.Authorization = 'Bearer ' + this.$store.getters.access_token
  },
  methods: {
    /**表格处理*/
    addSelectedRow() {
      if (this.selectedRows.length > 0) {
        this.selectedRows.forEach((selectedRow) => {
          const index = this.tableData.indexOf(selectedRow);
          if (index !== -1) {
            this.onAddItem(selectedRow)
          }
        });
      } else if (Object.keys(this.selectedRow).length !== 0){
        this.onAddItem(this.selectedRow)
      } else {
        this.$message({
          type: "warning",
          message: "请选择一条数据!"
        });
      }
    },
    clearTableData() {
      this.tableData = [];
    },
    onAddItem(val) {
      // 添加新资料
      if (!this.tableData) this.tableData = []
      this.tableData.push({
        name: val.name || '',
        compare: val.compare || 1,
        fileList: val.fileList || [],
      })
    },
    deleteSelectedRows() {
      if (this.selectedRows.length > 0) {
        this.selectedRows.forEach((selectedRow) => {
          const index = this.tableData.indexOf(selectedRow);
          if (index !== -1) {
            this.tableData.splice(index, 1);
          }
        });
      } else if (Object.keys(this.selectedRow).length !== 0){
        const index = this.tableData.indexOf(this.selectedRow);
        if (index !== -1) {
          this.tableData.splice(index, 1);
        }
      } else {
        this.$message({
          type: "warning",
          message: "请选择一条数据!"
        });
      }
    },
    updateSelectedRows(selection) {
      this.selectedRows = selection;
    },
    handleCurrentChange(selection){
      this.selectedRow = selection;
    },

    /**项目选择页面*/
    showProjectDialog() {
      this.projectDialog = true
      this.$refs.ChoseProject.initParams({
        isGCProjectApproved: true,//结算送审是否审批完成
        hasNotGCReport: true,//未生成审计报告
        isEngineering: true, //是否是工程审计
        isTermination: false
      });
    },
    closeProjectDialog() {
      this.projectDialog = false
      console.log(this.form)
    },
    projectDataHandle(row){
      this.projectDialog = false;
      let form = this.form;

      form.auditedUserNames = row.auditedUserNames;
      form.auditTypeSub = row.auditTypeSub;
      form.assistCompanyName = row.assistCompanyName;
      form.auditedCompanyName = row.auditedCompanyName;
      form.projectId = row.projectId;
      form.projectName = row.projectName;
      form.tenureStartDate = row.tenureStartDate;
      form.tenureEndDate = row.tenureEndDate;
      this.form = form;
      this.auditView = "ReportAuditType" + row.auditType;
      getByProjectId(row.projectId).then((res)=>{
        this.tableData = res.data.data;
      });
    },
    init(row,isHidden){
      this.isHidden = isHidden;
      this.$nextTick(async () => {
        if (row.reportId){
          const response = await getReport(row.reportId);
          this.$set(this, "form", response.data.data);
          this.fileList = this.form.attachments;
          this.fileList.forEach((item) =>{
            item.name = item.fileName;
            item.url = item.fileUrl;
          })

          // 打开页面后再加载tableData,避免出现文本框渲染错误的情况
          if (this.form.projectReportAttachments && this.form.projectReportAttachments.length > 0) {
            this.loading = true
            setTimeout(() => {
              this.tableData = this.form.projectReportAttachments || []
              this.tableData.forEach(item => {
                item.fileList = []
                item.attachments.forEach(col => {
                  item.fileList.push({name: col.fileName, url: col.fileUrl})
                })
              })
              this.loading = false
            }, 500)
          }
        }
        this.dialog = true;
      })
    },
    cancelDialog(){
      this.dialog = false;
      this.form = {};
      this.fileList = [];
      this.clearTableData();
      this.$refs['dataForm'].resetFields()
      this.$emit('cancelDialog', {})
    },
    saveEngineering() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.form.attachments = [];
          console.log(this.fileList)
          this.fileList.forEach(file => {
            this.form.attachments.push({fileName: file.name, fileUrl: file.url})
          })

          this.form.projectReportAttachments = []
          this.tableData.forEach((item, i) => {
            item.attachments = []
            if (item.fileList) {
              item.fileList.forEach(file => {
                item.attachments.push({fileName: file.name, fileUrl: file.url})
              })
            }
            this.form.projectReportAttachments.push(item)
          })
          console.log(this.form)
          this.form.isEngineering = 1;
          this.loading = true;
          saveEngineering(this.form).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.loading = false;
            this.cancelDialog();
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    submitEngineering(){
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.form.attachments = [];
          this.fileList.forEach(file => {
            this.form.attachments.push({fileName: file.name, fileUrl: file.url})
          })
          this.form.projectReportAttachments = []
          this.tableData.forEach((item, i) => {
            item.attachments = []
            if (item.fileList) {
              item.fileList.forEach(file => {
                item.attachments.push({fileName: file.name, fileUrl: file.url})
              })
            }
            this.form.projectReportAttachments.push(item)
          })
          this.form.isEngineering = 1;
          this.loading = true;
          submitEngineering(this.form).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.loading = false;
            this.cancelDialog();
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    /**
     * 文件上传
     */
    handleSuccess(response, file, fileList){
      console.info(response);
      if (!this.fileList) {
        this.fileList = [{url: response.data.url, name: response.data.fileName}]
      } else {
        this.fileList.push({url: response.data.url, name: response.data.fileName})
      }
    },
    handleTableSuccess(e, v) {
      if (!this.tableData[v].fileList) {
        this.tableData[v].fileList = [{url: e.data.url, name: e.data.fileName}]
        console.log(this.tableData);
      } else {
        this.tableData[v].fileList.push({url: e.data.url, name: e.data.fileName})
        console.log(this.tableData);
      }
    },
    handleRemove(file, fileList,i) {
      this.fileList.forEach((item, v) => {
        console.log(111);
        if (file.url === item.url) this.fileList.splice(v, 1)
      })
    },
    handleTableRemove(file, fileList,i){
      this.tableData[i].fileList.forEach((item, v) => {
        if (file.url === item.url) this.tableData[i].fileList.splice(v, 1)
      })
    },
    handlePreview(file) {
      const a = document.createElement('a');
      let url = file.url ? file.url : file.response.data.url;
      console.log(url);      // let fileName = '你想要的文件名.docx'; // 这里设置你想要的文件名，包括扩展名
      a.setAttribute('download', file.name);
      a.setAttribute('href', url);
      a.click();
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
  }
}
</script>
<style>

</style>
